package cn.zf233.jwtshiro.config.shiro.open;

import cn.zf233.jwtshiro.entity.User;
import cn.zf233.jwtshiro.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

/**
 * Created by zf233 on 2021/7/12
 */
@Slf4j
public class OpenRealm extends AuthorizingRealm {

    private final UserService userService;

    public OpenRealm(UserService userService) {
        this.userService = userService;
    }

    /**
     * 社交登陆验证
     * 只要存在openId所属用户即代表信息验证通过
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        OpenToken openToken = (OpenToken) authenticationToken;
        String openId = (String) openToken.getPrincipal();
        log.info("准备验证用户:'{}' (OpenId)" + openId);
        log.info("Token信息如下:'" + openId + "'");
        User result = userService.getUserByOpenId(openId);
        if (result == null) {
            log.info("用户不存在");
            throw new UnknownAccountException("不存在的用户");
        }
        // 用户存在即通过
        log.info("用户信息验证通过" );
        return new SimpleAuthenticationInfo(result, openId, getName());
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection collection) {
        return null;
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof OpenToken;
    }
}